/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.lswms.interceptor;

import com.lswms.annotation.Login;
import com.lswms.common.exception.ErrorCode;
import com.lswms.common.exception.RenException;
import com.lswms.redis.SysParamsRedis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private SysParamsRedis sysParamsRedis;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isBlank(userId)){
        	userId = request.getParameter("userId");
        }
        //token为空
        if(StringUtils.isBlank(token)){
            throw new RenException(ErrorCode.TOKEN_NULL);
        }
        //userId
        if(StringUtils.isBlank(userId)){
        	throw new RenException(ErrorCode.USERID_NULL);
        }

        //查询token信息
        String redisToken = sysParamsRedis.get("userinfo:"+userId);
        if(StringUtils.isBlank(redisToken)){
        	throw new RenException(ErrorCode.NOT_LOGIN);
        }
        if(!token.equals(redisToken)){
        	throw new RenException(ErrorCode.LOGIN_AGAIN);
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, userId);

        return true;
    }
}
